package com.lagou.service;

import com.lagou.codec.RpcDecoder;
import com.lagou.codec.RpcEncoder;
import com.lagou.handler.UserServiceHandler;
import com.lagou.request.RpcRequest;
import com.lagou.series.JSONSerializer;
import com.lagou.series.Serializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

/**
 * @author xsl
 * @date 2021/3/13 14:52
 * @Description: UserServiceImpl
 */
@Service
public class UserServiceImpl implements IUserService, ApplicationContextAware {

    private ApplicationContext applicationContext;
    @Override
    public String sayHello(String msg) {
        System.out.println("调用方法参数 =====：" + msg);
        return "调用成功参数 =====：" + msg;
    }

    public void startServer(String ip, int port) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        Serializer serializer = new JSONSerializer();
        ServerBootstrap bootstrap = new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, serializer));
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, serializer));
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new StringDecoder());
                        //把自定义的ChannelHandler添加到通道中
                        pipeline.addLast(applicationContext.getBean(UserServiceHandler.class));
                    }
                });
        bootstrap.bind(ip, port).sync();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
